package server

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/go-kratos/kratos/v2/transport/http"
	stdHttp "net/http"
	"strings"
)

func LocalHttpRequestFilter() http.FilterFunc {
	return func(next stdHttp.Handler) stdHttp.Handler {
		return stdHttp.HandlerFunc(func(w stdHttp.ResponseWriter, r *stdHttp.Request) {
			r.Header.Add("X-RemoteAddr", strings.Split(r.RemoteAddr, ":")[0])
			next.ServeHTTP(w, r)
		})
	}
}

func LocalHttpRequestMiddleware() middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
			if tp, ok := transport.FromServerContext(ctx); ok {
				println(fmt.Sprintf("remote_addr: %v", tp.RequestHeader().Get("RemoteAddr")))
			}
			return handler(ctx, req)
		}
	}
}
